<script setup>
import { inject, ref, reactive } from "vue";
import { useFetch, useStorage, useIntervalFn } from "@vueuse/core";

const item = reactive({
    account: "",
    auth_code: "",
    parameter: "",
    checked: false,
});

const alert = inject("alert");
const index = inject("index");

const countTime = ref(60);
const captchaText = ref("获取验证码");

const { pause, resume, isActive } = useIntervalFn(
    () => {
        if (countTime.value > 1) {
            countTime.value--;
            captchaText.value = `${countTime.value}S后重新获取`;
        } else {
            countTime.value = 60;
            captchaText.value = "获取验证码";

            // 倒计时为0时，触发计时器的暂停方法
            pause();
        }
    },
    1000, // 计时器触发的间隔时间
    { immediate: false }, // 首次是否触发
);

const submit = async () => {
    if (item.account === "") {
        alert.submit(false, "手机号为空");
        return;
    }

    if (item.auth_code === "") {
        alert.submit(false, "验证码为空");
        return;
    }

    if (item.parameter === "") {
        alert.submit(false, "未获取验证码");
        return;
    }

    if (item.checked !== true) {
        alert.submit(false, "未勾选协议");
        return;
    }

    const { error, data } = await useFetch("/api/login").post(item).json();

    if (error.value) {
        alert.submit(false, error.value);
        return;
    }

    if (data.value.status !== 200) {
        alert.submit(false, data.value.msg);
        return;
    }

    alert.submit(true, "注册成功");
    console.log("register", data.value);

    useStorage("auth").value = data.value.auth;
    useStorage("token").value = data.value.access_token;

    getInfo();
};

const x = async () => {
    if (item.account === "") {
        alert.submit(false, "手机号为空");
        return;
    }

    const { error, data } = await useFetch("/api/auth/code").post(item).json();

    if (error.value) {
        alert.submit(false, error.value);
        return;
    }

    if (data.value.status !== 200) {
        alert.submit(false, data.value.msg);
        return;
    }

    alert.submit(true, "发送成功");
    item.parameter = data.value.parameter;

    captchaText.value = `${countTime.value}s后重新获取`;
    // 恢复计时器活动状态
    resume();
};

const getInfo = async () => {
    const { error, data } = await useFetch("/api/user/info", {
        beforeFetch({ url, options, cancel }) {
            const myToken = useStorage("token").value;
            if (!myToken) {
                cancel();
            }

            options.headers = {
                ...options.headers,
                Authorization: `Bearer ${myToken}`,
            };

            return {
                options,
            };
        },
    })
        .get()
        .json();

    if (error.value) {
        alert.submit(false, error.value);
        return;
    }

    if (data.value.status !== 200) {
        alert.submit(false, data.value.msg);
        return;
    }

    useStorage("account").value = data.value.data.account;
    if (data.value.data.member) {
        useStorage("member").value = data.value.data.member;
    }

    // 切换页面
    index.value = 0;
};
</script>

<template>
    <div class="w-full h-screen flex flex-row justify-center items-center">
        <div
            class="w-full max-w-sm p-10 m-auto mx-auto bg-iso-gray-900 text-white border border-iso-gray-500 rounded-lg relative"
        >
            <span
                class="absolute right-5 top-2.5 text-white cursor-pointer"
                @click="index = 0"
            >
                <svg
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke-width="1.5"
                    stroke="currentColor"
                    class="size-5"
                >
                    <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        d="M6 18 18 6M6 6l12 12"
                    />
                </svg>
            </span>
            <div class="flex justify-center mx-auto">账号注册</div>

            <form class="mt-6">
                <div>
                    <input
                        type="text"
                        class="block w-full px-4 py-2 mt-2 bg-iso-gray-900 border border-iso-gray-400 rounded-full focus:outline-none placeholder:text-sm"
                        v-model="item.account"
                        placeholder="输入手机号"
                    />
                </div>

                <div class="mt-6">
                    <div class="relative">
                        <span
                            class="absolute right-4 top-3 text-xs cursor-pointer"
                            :class="[
                                isActive ? 'text-gray-500' : 'text-blue-500',
                            ]"
                            @click="x"
                            :disabled="isActive"
                        >
                            {{ captchaText }}
                        </span>

                        <input
                            type="text"
                            class="block w-full px-4 py-2 mt-2 bg-iso-gray-900 border border-iso-gray-400 rounded-full focus:outline-none placeholder:text-sm"
                            v-model="item.auth_code"
                            placeholder="输入验证码"
                        />
                    </div>
                </div>

                <div class="mt-6">
                    <button
                        type="button"
                        @click="submit"
                        class="flex items-center justify-center w-full px-6 py-2 text-sm font-medium text-white transition-colors duration-300 transform bg-iso-blue-600 rounded-full hover:bg-blue-400 focus:bg-blue-400 focus:outline-none"
                    >
                        <span class="hidden mx-2 sm:inline"> 注册 </span>
                    </button>
                </div>

                <div class="mt-6">
                    <div class="flex items-center">
                        <input
                            type="checkbox"
                            id="checkbox"
                            v-model="item.checked"
                        />

                        <label
                            for="checkbox"
                            class="px-2 text-gray-500 text-xs cursor-pointer"
                        >
                            已阅读并同意
                            <router-link
                                to="/x/legal"
                                class="text-iso-blue-600"
                            >
                                用户协议
                            </router-link>
                            <span class="text-blue-600 mx-1">/</span>
                            <router-link
                                to="/x/privacy"
                                class="text-iso-blue-600"
                            >
                                隐私政策
                            </router-link>
                        </label>
                    </div>
                </div>
            </form>
        </div>
    </div>
</template>
